<template>
  <div class="container">
    <BackToHomeButton/>
    <h1>Jtt模拟器</h1>

    <!-- 布局 -->
    <div class="content">
      <!-- 使用 div 包裹注册指令按钮，确保它在聊天框左边 -->
      <div class="button-container">


        <!-- 输入框和下拉框 -->
        <div class="input-group">
          <input v-model="address" type="text" placeholder="请输入地址" class="input-field"/>
          <input v-model="simNo" type="text" placeholder="请输入设备 ID" class="input-field"/>
          <!-- 下拉框 -->
          <select v-model="version" class="input-field">
            <option value="2013">2013</option>
            <option value="2019">2019</option>
          </select>
          <!--websocket连接-->
          <button @click="toggleConnection" :class="isConnected ? 'disconnect-btn' : 'connect-btn'">
            {{ isConnected ? '断开' : '连接' }}
          </button>
        </div>
      </div>
      <!--指令框-->
      <div class="cmd-box">
        <button @click="openModal" class="register-btn">注册0x0100</button>
        <button @click="openAuth" class="register-btn">鉴权0x0102</button>
        <button @click="openHeart" class="register-btn">心跳0x0002</button>
        <button @click="toggleHeartConnection" :class="heartSchedule ? 'disconnect-btn' : 'connect-btn'">
          {{ heartSchedule ? '关闭定时心跳' : '启动定时心跳' }}
        </button>
      </div>

      <!-- 聊天框 -->
      <div class="chat-box" ref="chatBox">
        <div v-for="(message, index) in chatMessages" :key="index" :class="['chat-message', message.isSent ? 'sent' : 'received']" @dblclick="decodeMessage(index)">
          <div class="message-time">{{ message.timestamp }}</div>
          <div class="message-content">{{ message.decoded ? message.content : message.original }}</div>
        </div>
      </div>

      <!-- 输入框和发送按钮 -->
      <div class="input-container">
        <textarea v-model="hexInput" placeholder="请输入或获取 Hex 数据" class="hex-input"></textarea>
        <button @click="sendHexData" class="send-btn">发送</button>
      </div>
    </div>

  </div>

  <!-- 注册指令弹框 -->
  <div v-if="isModalVisible" class="modal">
    <div class="modal-content">
      <button @click="closeBase('isModalVisible')" class="close-btn">X</button>
      <h2>请输入设备信息</h2>
      <form @submit.prevent="submitRegisterForm">
        <div>
          <label for="deviceId">设备号：</label>
          <input v-model="modalData.simNo" type="text" id="deviceId" placeholder="请输入设备号" required/>
        </div>
        <div>
          <label for="versionFlag">版本标识：</label>
          <input v-model="modalData.versionFlag" type="number" id="versionFlag" placeholder="请输入版本标识" required/>
        </div>
        <div>
          <label for="provinceId">省份 ID：</label>
          <input v-model="modalData.provinceId" type="number" id="provinceId" placeholder="请输入省份 ID" required/>
        </div>
        <div>
          <label for="cityId">城市 ID：</label>
          <input v-model="modalData.cityId" type="number" id="cityId" placeholder="请输入城市 ID" required/>
        </div>
        <div>
          <label for="manufacturerId">制造商 ID：</label>
          <input v-model="modalData.manufacturerId" type="text" id="manufacturerId" placeholder="请输入制造商 ID" required/>
        </div>
        <div>
          <label for="terminalModelNo">终端型号：</label>
          <input v-model="modalData.terminalModelNo" type="text" id="terminalModelNo" placeholder="请输入终端型号" required/>
        </div>
        <div>
          <label for="terminalId">终端 ID：</label>
          <input v-model="modalData.terminalId" type="text" id="terminalId" placeholder="请输入终端 ID" required/>
        </div>
        <div>
          <label for="color">颜色：</label>
          <input v-model="modalData.color" type="number" id="color" placeholder="请输入颜色" required/>
        </div>
        <div>
          <label for="plateNo">车牌号：</label>
          <input v-model="modalData.plateNo" type="text" id="plateNo" placeholder="请输入车牌号" required/>
        </div>
        <button type="submit">提交</button>
      </form>
    </div>
  </div>


  <!--鉴权弹窗-->
  <div v-if="isAuthVisible" class="modal">
    <div class="modal-content">
      <button @click="closeBase('isAuthVisible')" class="close-btn">X</button>
      <h2>请输入设备信息</h2>
      <form @submit.prevent="submitAuthForm">
        <div>
          <label for="deviceId">设备号：</label>
          <input v-model="authData.simNo" type="text" id="deviceId" placeholder="请输入设备号" required/>
        </div>
        <div>
          <label for="versionFlag">版本标识：</label>
          <input v-model="authData.versionFlag" type="number" id="versionFlag" placeholder="请输入版本标识" required/>
        </div>
        <div>
          <label for="authCode">鉴权码：</label>
          <input v-model="authData.authCode" type="text" id="authCode" placeholder="鉴权码" required/>
        </div>

        <div v-if="authData.versionFlag===1">
          <label for="imei">终端imei：</label>
          <input v-model="authData.imei" type="text" id="imei" placeholder="终端imei" required/>
        </div>
        <div v-if="authData.versionFlag===1">
          <label for="softwareVersion">软件版本号：</label>
          <input v-model="authData.softwareVersion" type="text" id="softwareVersion" placeholder="软件版本号" required/>
        </div>

        <button type="submit">提交</button>
      </form>
    </div>
  </div>

  <!--心跳配置-->
  <div v-if="isHeartVisible" class="modal">
    <div class="modal-content">
      <button @click="closeBase('isHeartVisible')" class="close-btn">X</button>
      <h2>请输入设备信息</h2>
      <form @submit.prevent="submitHeartForm">
        <div>
          <label for="deviceId">设备号：</label>
          <input v-model="heartData.simNo" type="text" id="deviceId" placeholder="请输入设备号" required/>
        </div>
        <div>
          <label for="versionFlag">版本标识：</label>
          <input v-model="heartData.versionFlag" type="number" id="versionFlag" placeholder="请输入版本标识" required/>
        </div>
        <div>
          <label for="idle">心跳间隔：</label>
          <input v-model="heartData.idle" type="number" id="idle" placeholder="心跳间隔" required/>
        </div>
        <button type="submit">提交</button>
      </form>
    </div>
  </div>


</template>

<style scoped>
.container {
  padding: 20px;
  background: #2c8e63;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 80%;
  max-width: 800px;
}

.button-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.register-btn {
  margin: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
}

.input-group {
  display: flex;
  gap: 10px;
  margin-left: 20px;
}

.input-field {
  padding: 8px;
  border-radius: 5px;
  border: 1px solid #ccc;
  width: 150px;
}

.connect-btn {
  padding: 8px;
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
}

.disconnect-btn {
  padding: 8px;
  background-color: red;
  color: white;
  border: none;
  cursor: pointer;
}

.chat-box {
  width: 100%;
  height: 300px;
  background-color: #f4f4f4;
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
  /* 增加 scroll-behavior：smooth，确保滚动平滑 */
  scroll-behavior: smooth;
}

.cmd-box {
  background-color: #f4f4f4;
  border: 1px solid #ccc;
  margin-bottom: 20px;
}

.chat-message {
  max-width: 70%;
  padding: 10px;
  border-radius: 8px;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.chat-message.sent {
  background-color: #b3f5b7;
  align-self: flex-end;
  text-align: left;
}

.chat-message.received {
  background-color: #e1f5fe;
  align-self: flex-start;
  text-align: left;
}

.message-time {
  font-size: 12px;
  color: #999;
  text-align: center;
}

.message-content {
  padding: 10px;
  border-radius: 8px;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.input-container {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

.hex-input {
  width: 80%;
  height: 100px;
  padding: 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
  resize: none;
}

.send-btn {
  width: 15%;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
  margin-left: 10px;
}

.send-btn:hover {
  background-color: #45a049;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  margin: 20px;
  padding-bottom: 20px;
  border-radius: 8px;
  width: 300px;
  text-align: center;
}

input, button {
  margin-top: 10px;
}

button {
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

/* 关闭按钮 */
.close-btn {
  float: right;
  font-size: 24px;
  background: none;
  border: none;
  color: #aaa;
  cursor: pointer;
  padding-top: 0px;
}

.close-btn:hover {
  color: black;
  background-color: white;
}


</style>

<script setup>
import {nextTick, ref, watch} from 'vue';
import {postData} from './utils/request';  // 引入封装的 postData 方法


const hexInput = ref('');
const isModalVisible = ref(false);
const isAuthVisible = ref(false);
const isHeartVisible = ref(false);
const isConnected = ref(false);
const simNo = ref('1000000001');
const version = ref('2019');
const versionFlag = ref(1);   // 对应的 versionFlag，初始值为 1
const address = ref('127.0.0.1:8866');
const authCode = ref('ABC1234567');
const chatMessages = ref([]);
const socketRef = ref(null);
const chatBox = ref(null);
const heartSchedule = ref(false);
const softwareVersion = ref('');
const imei = ref('');

// 弹窗
const showMap = ref({
  isModalVisible: isModalVisible,
  isAuthVisible: isAuthVisible,
  isHeartVisible: isHeartVisible,
});

// 关闭按钮
const closeBase = (modalName) => {
  showMap.value[modalName] = false;
};


// 监听下拉框的变化
watch(version, (newVersion) => {
  // 根据 version 设置 versionFlag
  versionFlag.value = newVersion === '2019' ? 1 : 0;
});
const connectWebSocket = () => {
  const url = `ws://localhost:8787/ws/connect?deviceId=${simNo.value}&address=${address.value}`;
  const socket = new WebSocket(url);

  socket.onopen = () => {
    isConnected.value = true;
    chatMessages.value.push({original: 'WebSocket 连接成功', decoded: false, isSent: false, timestamp: getCurrentTime()});
    scrollToBottom();  // 每次收到消息后滚动到最底部
  };

  socket.onerror = (error) => {
    chatMessages.value.push({original: `WebSocket 错误: ${error.message}`, decoded: false, isSent: false, timestamp: getCurrentTime()});
    scrollToBottom();  // 每次收到消息后滚动到最底部
  };

  // websocket鉴听数据
  socket.onmessage = (event) => {
    const response = JSON.parse(event.data);
    try {
      const data = JSON.parse(response.data);
      if (data && typeof data === "object") {
        if (data.authCode) {
          // 是否有鉴权码
          authCode.value = data.authCode;
        }
        if (data.hex) {
          // 是否有hex
          response.data = data.hex;
        }
      }
    } catch (e) {
      console.log('没有授权码');
    }

    chatMessages.value.push({original: response.data, decoded: false, isSent: false, timestamp: getCurrentTime()});
    scrollToBottom();  // 每次收到消息后滚动到最底部
  };

  socket.onclose = () => {
    isConnected.value = false;
    chatMessages.value.push({original: 'WebSocket 连接已关闭', decoded: false, isSent: false, timestamp: getCurrentTime()});
    scrollToBottom();  // 每次收到消息后滚动到最底部
  };

  socketRef.value = socket;
};

// 断开websocket
const disconnectWebSocket = () => {
  if (socketRef.value) {
    socketRef.value.close();
  }
  isConnected.value = false;
};

// 切换连接状态
function toggleConnection() {
  if (isConnected.value) {
    disconnectWebSocket();
  } else {
    connectWebSocket();
  }
}

// 滚动到聊天框底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatBox.value) {
      chatBox.value.scrollTop = chatBox.value.scrollHeight;
    }
  });
};

// 解码数据
const decodeMessage = async (index) => {
  const message = chatMessages.value[index];

  // 如果已经解码过，直接返回
  if (message.decoded) {
    chatMessages.value[index].decoded = false;
    return;
  }

  const hexData = message.original;  // 获取原始数据（A）

  try {
    // 发送 POST 请求获取解码数据
    const response = await postData('/api/simulate/decodeHex', {hex: hexData});

    // 将解码后的数据替换原始数据
    chatMessages.value[index].content = response.data;  // 设置为解码后的内容 (B)
    chatMessages.value[index].decoded = true;  // 设置已解码标志
  } catch (error) {
    console.error('解码请求失败:', error);
  }
};


// 注册数据中的输入数据
const modalData = ref({
  simNo: simNo,
  versionFlag: versionFlag,
  provinceId: 1,
  cityId: 2,
  manufacturerId: '123456',
  terminalModelNo: '123456',
  terminalId: '1234567',
  color: 1,
  plateNo: '粤B123456',
});

// 鉴权数据
const authData = ref({
  simNo: simNo,
  versionFlag: versionFlag,
  authCode: authCode,
  imei: imei,
  softwareVersion: softwareVersion,
});

// 心跳配置
const heartData = ref(
    {
      simNo: simNo,
      versionFlag: versionFlag,
      idle: 30
    }
);


const openModal = () => {
  isModalVisible.value = true;
  modalData.value = {
    simNo: simNo,
    versionFlag: versionFlag.value,
    provinceId: 1,
    cityId: 2,
    manufacturerId: '123456',
    terminalModelNo: '123456',
    terminalId: '1234567',
    color: 1,
    plateNo: '粤B123456',
  };
};

const openAuth = () => {
  isAuthVisible.value = true;
  authData.value = {
    simNo: simNo,
    versionFlag: versionFlag.value,
    authCode: authCode
  };
}

const openHeart = () => {
  isHeartVisible.value = true;
  heartData.value = {
    simNo: simNo,
    versionFlag: versionFlag.value,
    idle: 30
  }
}


const getCurrentTime = () => {
  const now = new Date();
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');
  const milliseconds = now.getMilliseconds().toString().padStart(3, '0');
  return `${hours}:${minutes}:${seconds}.${milliseconds}`;
};

// 提交表单的通用函数
const submitForm = async (url, data, onSuccess, onError) => {
  const requestData = {
    cmdId: data.cmdId,  // cmdId 从数据中传入
    data: JSON.stringify(data),
  };

  try {
    const response = await postData(url, requestData);
    hexInput.value = response.data;
    if (onSuccess) onSuccess(response);  // 执行成功的回调
    await sendHexData();
  } catch (error) {
    console.error('请求失败:', error);
    if (onError) onError(error);  // 执行失败的回调
  }
};

// 提交注册表单
const submitRegisterForm = async () => {
  const data = {
    cmdId: 256, // 默认值
    ...modalData.value,
  };
  const onSuccess = () => {
    closeBase('isModalVisible');
  };
  const onError = (error) => {
    console.error('注册指令请求失败:', error);
  };
  // 调用通用的提交函数
  await submitForm('/api/simulate/genHex', data, onSuccess, onError);
};

// 提交鉴权数据
const submitAuthForm = async () => {
  const data = {
    cmdId: 258, // 默认值
    ...authData.value,// 展开 authData 中的内容
  };
  // 最后成这样 {cmdId: 258, simNo: '1000000001', versionFlag: 1, authCode: 'ABC1234567'}
  const onSuccess = () => {
    closeBase('isAuthVisible');
  };
  const onError = (error) => {
    console.error('鉴权请求失败:', error);
  };
  // 调用通用的提交函数
  await submitForm('/api/simulate/genHex', data, onSuccess, onError);
};


// 定时获取心跳然后通过websocket发送，保持心跳
const submitHeartForm = async () => {
  const data = {
    cmdId: 2, // 默认值
    ...heartData.value,// 展开 heartData 中的内容
  };
  // 最后成这样 {cmdId: 258, simNo: '1000000001', versionFlag: 1, authCode: 'ABC1234567'}
  const onSuccess = () => {
    closeBase('isHeartVisible');
  };
  const onError = (error) => {
    console.error('请求失败:', error);
  };
  // 调用通用的提交函数
  await submitForm('/api/simulate/genHex', data, onSuccess, onError);
};

// 定时器ID
let timerId = null;

// 执行心跳函数
const executeHeartBeat = async () => {
  console.log('发送心跳包:', new Date().toLocaleTimeString());
  if (heartSchedule.value){
    await submitHeartForm();
  }
};


// 启动定时任务
const startHeartBeat = () => {
  const idleTime = heartData.value.idle;
  heartSchedule.value = true;
  if (idleTime <= 0) {
    console.error('Idle 值必须大于 0');
    return;
  }

  // 清除之前的定时器
  if (timerId) {
    clearInterval(timerId);
  }

  // 启动新的定时器
  timerId = setInterval(executeHeartBeat, idleTime * 1000);
};

// 停止定时器
const stopHeartBeat = () => {
  // 定时任务关闭
  heartSchedule.value = false;
  if (timerId) {
    clearInterval(timerId);
    timerId = null;
    console.log('定时任务已停止');
  } else {
    console.log('没有定时任务在运行');
  }
};
// 启动/关闭定时心跳
function toggleHeartConnection() {
  if (heartSchedule.value) {
    stopHeartBeat();
  } else {
    startHeartBeat();
  }
}


// websocket发送hex数据 发送按钮
const sendHexData = async () => {
  const hexData = hexInput.value;
  if (!hexData) return;

  if (socketRef.value && socketRef.value.readyState === WebSocket.OPEN) {
    socketRef.value.send(hexData);
    chatMessages.value.push({original: hexData, decoded: false, isSent: true, timestamp: getCurrentTime()});
  } else {
    chatMessages.value.push({original: 'WebSocket 尚未连接', decoded: false, isSent: false, timestamp: getCurrentTime()});
  }
  scrollToBottom();
};


</script>
